package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private Button btnSelectCity, btnSelectSchool, btnSelectCampus, btnConfirm;
    private List<City> cityList = new ArrayList<>();
    private List<School> schoolList = new ArrayList<>();
    private List<Campus> campusList = new ArrayList<>();
    private City selectedCity = null;
    private School selectedSchool = null;
    private Campus selectedCampus = null;
    private OkHttpClient client = new OkHttpClient();

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSelectCity = findViewById(R.id.btnSelectCity);
        btnSelectSchool = findViewById(R.id.btnSelectSchool);
        btnSelectCampus = findViewById(R.id.btnSelectCampus);
        btnConfirm = findViewById(R.id.btnConfirm);
        initCityData();
        btnSelectCity.setOnClickListener(v -> showCityDialog());
        btnSelectSchool.setOnClickListener(v -> showSchoolDialog());
        btnSelectCampus.setOnClickListener(v -> showCampusDialog());
        btnConfirm.setOnClickListener(v -> onConfirm());
    }

    private void initCityData() {
        cityList.clear();
        cityList.add(new City(1, "北京", "010-67781234"));
        cityList.add(new City(2, "上海", "021-63031234"));
        cityList.add(new City(3, "常州", "0519-88811711"));
        cityList.add(new City(4, "南京", "025-84481234"));
        cityList.add(new City(5, "苏州", "0512-65111234"));
        cityList.add(new City(6, "无锡", "0510-82791234"));
        cityList.add(new City(7, "广州", "020-84281234"));
    }

    private void showCityDialog() {
        String[] names = new String[cityList.size()];
        for (int i = 0; i < cityList.size(); i++) names[i] = cityList.get(i).name;
        new AlertDialog.Builder(this)
                .setTitle("选择城市")
                .setItems(names, (d, which) -> {
                    selectedCity = cityList.get(which);
                    btnSelectCity.setText(selectedCity.name);
                    btnSelectSchool.setText("选择学校");
                    btnSelectCampus.setText("选择校区");
                    selectedSchool = null;
                    selectedCampus = null;
                    schoolList.clear();
                    campusList.clear();
                    fetchSchoolList(selectedCity.id);
                })
                .show();
    }

    private void showSchoolDialog() {
        if (schoolList.isEmpty()) {
            Toast.makeText(this, "请先选择城市", Toast.LENGTH_SHORT).show();
            return;
        }
        String[] names = new String[schoolList.size()];
        for (int i = 0; i < schoolList.size(); i++) names[i] = schoolList.get(i).name;
        new AlertDialog.Builder(this)
                .setTitle("选择学校")
                .setItems(names, (d, which) -> {
                    selectedSchool = schoolList.get(which);
                    btnSelectSchool.setText(selectedSchool.name);
                    btnSelectCampus.setText("选择校区");
                    selectedCampus = null;
                    campusList.clear();
                    fetchCampusList(selectedSchool.id);
                })
                .show();
    }

    private void showCampusDialog() {
        if (campusList.isEmpty()) {
            Toast.makeText(this, "请先选择学校", Toast.LENGTH_SHORT).show();
            return;
        }
        String[] names = new String[campusList.size()];
        for (int i = 0; i < campusList.size(); i++) names[i] = campusList.get(i).name;
        new AlertDialog.Builder(this)
                .setTitle("选择校区")
                .setItems(names, (d, which) -> {
                    selectedCampus = campusList.get(which);
                    btnSelectCampus.setText(selectedCampus.name);
                })
                .show();
    }

    private void fetchSchoolList(int cityId) {
        schoolList.clear();
        btnSelectSchool.setText("加载中...");
        btnSelectSchool.setEnabled(false);
        btnSelectCampus.setEnabled(false);
        String url = "https://school.lihua.com/api/cashier/getentlist";
        FormBody body = new FormBody.Builder()
                .add("city_id", String.valueOf(cityId))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> {
                    btnSelectSchool.setText("加载失败，重试");
                    btnSelectSchool.setEnabled(true);
                });
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body() != null ? response.body().string() : null;
                System.out.println("学校接口返回: " + resp);
                try {
                    if (resp == null || resp.trim().isEmpty()) {
                        runOnUiThread(() -> btnSelectSchool.setText("无数据"));
                        return;
                    }
                    JSONArray arr = null;
                    Object jsonObj = new JSONTokener(resp).nextValue();
                    if (jsonObj instanceof JSONArray) {
                        arr = (JSONArray) jsonObj;
                    } else if (jsonObj instanceof JSONObject) {
                        JSONObject obj = (JSONObject) jsonObj;
                        arr = obj.optJSONArray("data");
                        if (arr == null) arr = new JSONArray();
                    }
                    if (arr != null) {
                        for (int i = 0; i < arr.length(); i++) {
                            JSONObject obj = arr.optJSONObject(i);
                            if (obj != null && obj.has("id") && obj.has("name")) {
                                int schoolId = obj.optInt("id");
                                String schoolName = obj.optString("name");
                                
                                // 解析arrive_time数组（关键修复）
                                List<String> arriveTimes = new ArrayList<>();
                                JSONArray timeArray = obj.optJSONArray("arrive_time");
                                if (timeArray != null) {
                                    for (int j = 0; j < timeArray.length(); j++) {
                                        String time = timeArray.optString(j);
                                        if (time != null && !time.isEmpty()) {
                                            arriveTimes.add(time);
                                        }
                                    }
                                }
                                
                                schoolList.add(new School(schoolId, schoolName, arriveTimes));
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() -> btnSelectSchool.setText("解析失败"));
                }
                runOnUiThread(() -> {
                    btnSelectSchool.setText("选择学校");
                    btnSelectSchool.setEnabled(true);
                    btnSelectCampus.setEnabled(true);
                });
            }
        });
    }

    private void fetchCampusList(int schoolId) {
        campusList.clear();
        btnSelectCampus.setText("加载中...");
        btnSelectCampus.setEnabled(false);
        String url = "https://school.lihua.com/api/cashier/get_address_byid";
        FormBody body = new FormBody.Builder()
                .add("eid", String.valueOf(schoolId))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> btnSelectCampus.setText("加载失败，重试"));
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body() != null ? response.body().string() : null;
                System.out.println("校区接口返回: " + resp);
                try {
                    if (resp == null || resp.trim().isEmpty()) {
                        runOnUiThread(() -> btnSelectCampus.setText("无数据"));
                        return;
                    }
                    JSONArray arr = null;
                    Object jsonObj = new JSONTokener(resp).nextValue();
                    if (jsonObj instanceof JSONArray) {
                        arr = (JSONArray) jsonObj;
                    } else if (jsonObj instanceof JSONObject) {
                        JSONObject obj = (JSONObject) jsonObj;
                        arr = obj.optJSONArray("data");
                        if (arr == null) arr = new JSONArray();
                    }
                    if (arr != null) {
                        for (int i = 0; i < arr.length(); i++) {
                            JSONObject obj = arr.optJSONObject(i);
                            if (obj != null && obj.has("id") && obj.has("name")) {
                                campusList.add(new Campus(obj.optInt("id"), obj.optString("name")));
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() -> btnSelectCampus.setText("解析失败"));
                }
                runOnUiThread(() -> {
                    btnSelectCampus.setText("选择校区");
                    btnSelectCampus.setEnabled(true);
                });
            }
        });
    }

    private void onConfirm() {
        if (selectedCity == null || selectedSchool == null || selectedCampus == null) {
            Toast.makeText(this, "请完整选择城市、学校和校区", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(MainActivity.this, OrderVerificationActivity.class);
        intent.putExtra("cityName", selectedCity.name);
        intent.putExtra("schoolName", selectedSchool.name);
        intent.putExtra("campusName", selectedCampus.name);
        intent.putExtra("schoolId", selectedSchool.id); 
        
        // 改为获取当前选择学校的时间数组（关键修复）
        ArrayList<String> arriveTimes = new ArrayList<>(selectedSchool.getArriveTimes());
        intent.putStringArrayListExtra("arriveTimes", arriveTimes);
        
        startActivity(intent);
    }

    static class City {
        int id; String name; String tel;
        City(int id, String name, String tel) { this.id = id; this.name = name; this.tel = tel; }
    }
    static class School {
        int id; 
        String name;
        List<String> arriveTimes; // 改为存储时间数组
    
        // 构造方法更新为接收时间数组
        School(int id, String name, List<String> arriveTimes) { 
            this.id = id; 
            this.name = name; 
            this.arriveTimes = arriveTimes; 
        }
    
        // 新增获取时间数组的方法
        public List<String> getArriveTimes() {
            return arriveTimes;
        }
    }
    static class Campus {
        int id; String name;
        Campus(int id, String name) { this.id = id; this.name = name; }
    }
}